package com.gxa.ssm340.interceptor;


import com.gxa.ssm340.anno.RequiresPermission;
import com.gxa.ssm340.common.ErrorCode;
import com.gxa.ssm340.entity.dto.UserMenuDTO;
import com.gxa.ssm340.entity.pojo.Menu;
import com.gxa.ssm340.entity.vo.AdminMenusVO;
import com.gxa.ssm340.exception.BizException;
import com.gxa.ssm340.mapper.MenuMapper;
import com.gxa.ssm340.service.AdminService;
import com.gxa.ssm340.uitl.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;


/**
 * @author Lenovo
 */


public class PermissionInterceptor2 implements HandlerInterceptor {

    @Autowired
    MenuMapper menuMapper;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        Method method = ((HandlerMethod) o).getMethod();
        RequiresPermission annotation = method.getAnnotation(RequiresPermission.class);
        String value = annotation.value();




        System.out.println("PermissionInterceptor2拦截器开始工作");


        String phone = request.getHeader("phone");

        if (StringUtils.isEmpty(phone)){
            throw  new BizException(ErrorCode.NULL_TOKEN);
        }


        String requestURI = request.getRequestURI();

        List<UserMenuDTO> userMenuDTOS = menuMapper.selectAllMenusByPhone(phone);
        for (UserMenuDTO userMenuDTO : userMenuDTOS) {
            List<Menu> menus = userMenuDTO.getMenus();
            for (Menu menu : menus) {
                if (!StringUtils.isEmpty(menu.getMenuUrl()) && requestURI.equals(menu.getMenuUrl()) && value.equals(menu.getMenuName()) ){
                    return true;
                }
            }
        }

        throw new BizException(ErrorCode.VALIED_PERMISSION);
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //处理器操作的后置操作
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //处理完成后的必要操作
    }
}
